<template>
  <div class="student-form-container">
    <el-card>
      <template #header>
        <div class="form-header">
          <h2>{{ isEdit ? '编辑学生' : '添加学生' }}</h2>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
        class="student-form"
        :disabled="loading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentNo">
              <el-input v-model="form.studentNo" placeholder="请输入学号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age" :min="1" :max="100" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级" prop="classId">
              <el-select v-model="form.classId" placeholder="请选择班级">
                <el-option
                  v-for="item in classList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        
        <el-form-item label="家庭住址" prop="address">
          <el-input
            v-model="form.address"
            type="textarea"
            :rows="3"
            placeholder="请输入家庭住址"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
/**
 * 学生表单页面
 * 用于添加或编辑学生信息
 */
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getStudentDetail, createStudent, updateStudent } from '@/api/student'

export default {
  name: 'StudentForm',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const formRef = ref(null)
    
    // 是否为编辑模式
    const isEdit = computed(() => {
      return !!route.params.id
    })
    
    // 表单数据
    const form = reactive({
      id: undefined,
      studentNo: '',
      name: '',
      gender: 1,
      age: 18,
      classId: undefined,
      phone: '',
      email: '',
      address: ''
    })
    
    // 表单验证规则
    const rules = {
      studentNo: [
        { required: true, message: '请输入学号', trigger: 'blur' },
        { pattern: /^\d{8}$/, message: '学号格式不正确，应为8位数字', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度应在2-20个字符之间', trigger: 'blur' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      age: [
        { required: true, message: '请输入年龄', trigger: 'blur' },
        { type: 'number', min: 1, max: 100, message: '年龄应在1-100之间', trigger: 'blur' }
      ],
      classId: [
        { required: true, message: '请选择班级', trigger: 'change' }
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
      ]
    }
    
    // 班级列表
    const classList = ref([
      { id: 1, name: '计算机科学1班' },
      { id: 2, name: '计算机科学2班' },
      { id: 3, name: '软件工程1班' },
      { id: 4, name: '软件工程2班' }
    ])
    
    // 加载状态
    const loading = ref(false)
    
    // 初始化
    onMounted(() => {
      if (isEdit.value) {
        fetchStudentDetail()
      }
    })
    
    // 获取学生详情
    const fetchStudentDetail = () => {
      loading.value = true
      
      getStudentDetail(route.params.id).then(res => {
        // 填充表单
        Object.keys(form).forEach(key => {
          if (res[key] !== undefined) {
            form[key] = res[key]
          }
        })
        
        // 性别转换为数字类型
        if (res.gender === "男") {
          form.gender = 1
        } else if (res.gender === "女") {
          form.gender = 2
        }
        
        // 设置班级ID
        if (!form.classId && form.className) {
          const classItem = classList.value.find(c => c.name === form.className)
          if (classItem) {
            form.classId = classItem.id
          }
        }
      }).catch(err => {
        console.error('获取学生详情失败', err)
        ElMessage.error('获取学生详情失败')
      }).finally(() => {
        loading.value = false
      })
    }
    
    // 提交表单
    const submitForm = () => {
      formRef.value.validate((valid) => {
        if (!valid) {
          return
        }
        
        loading.value = true
        
        // 处理提交的数据
        const submitData = { ...form }
        
        // 性别转为字符串
        submitData.gender = submitData.gender === 1 ? "男" : "女"
        
        // 添加班级名称
        if (submitData.classId) {
          const classItem = classList.value.find(c => c.id === submitData.classId)
          if (classItem) {
            submitData.className = classItem.name
          }
        }
        
        const apiCall = isEdit.value 
          ? updateStudent(form.id, submitData)
          : createStudent(submitData)
        
        apiCall.then(() => {
          ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
          goBack()
        }).catch(err => {
          console.error('保存学生信息失败', err)
          ElMessage.error('保存学生信息失败')
        }).finally(() => {
          loading.value = false
        })
      })
    }
    
    // 重置表单
    const resetForm = () => {
      if (isEdit.value) {
        fetchStudentDetail()
      } else {
        formRef.value.resetFields()
      }
    }
    
    // 返回
    const goBack = () => {
      router.back()
    }
    
    return {
      formRef,
      isEdit,
      form,
      rules,
      classList,
      loading,
      submitForm,
      resetForm,
      goBack
    }
  }
}
</script>

<style scoped>
.student-form-container {
  max-width: 1000px;
  margin: 0 auto;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-header h2 {
  font-size: 18px;
  font-weight: bold;
  margin: 0;
}

.student-form {
  padding: 20px 0;
}
</style> 